#!/bin/sh
#set -x
echo `date`
hostip=`cat hosts.txt|grep -v "^#"`
ipcount=`cat hosts.txt|grep -v "^#"|wc -l`
/usr/bin/python /usr/sbin/cloudapi.py -shutdown ||error_exit
#/etc/init.d/cloud-management stop ||error_exit
while true
    do
         flag=0
             for ip in $hostip
               do
                 count=`ssh $ip virsh list|grep -v ^$|grep -v 'Id.*Name.*State'|grep -v "\---------"|wc -l`
                 if [ $count -eq 0 ];then
                 ssh $ip poweroff &
                 ((flag++))
                 echo "shuting down host" $ip
                 fi
               done
             if [ "$ipcount" -eq "$flag" ];then
               break
             fi
         sleep 10
     done

while true
        do
                flag=0
                for ip in $hostip
                        do
                                #status=`telnet $ip 22 < /dev/null 2>/dev/null | grep '\^' | wc -l`
                                count=`ping -c 3 $ip |grep ttl|wc -l`
                                if [ $count -eq 0 ]
                                then
                                #       echo "OK"
                                        ((flag++))
                                fi
                        done
                if [ "$ipcount" -eq "$flag" ];then
                    break
                fi
                sleep 10
        done

poweroff &
echo "Goodbye!!!"
exit 0
function error_exit {
   # Display error message and exit
   echo "${PROGNAME}:  $*" 1>&2
   exit 1
}
